var util = require('../../utils/util.js')
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var reload = true;
var dt_page = 1;
var dt_hasMore = true;
var dt_loadingMore = false;
var mt_page = 1;
var mt_hasMore = true;
var mt_loadingMore = false;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tc: 0,

    bottom_nav_data: [],
    isIphone_x: false,
    nav_bgColor: '#ffffff',

    imgDomain: app.globalData.imgDomain,
    curr: {
      dt: "curr",
      mt: ""
    },
    dongtaiData: [],
    hasDongtai: true,
    meitiData: [],
    hasMeiti: true,
    uid: 0,
    token: '',
    openid: '',
    canEdit: 0,

    wz_item_img_w_1: 0,
    wz_item_img_w_2: 0,
    wz_item_img_w_3: 0,
    wz_item_img_h_1: 0,
    wz_item_img_h_2: 0,
    wz_item_img_h_3: 0,
    

    album:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var tc = app.get_tc();
    wx.showLoading({
      title: '加载中',
      mask: 'true'
    })

    dt_page = 1;
    dt_hasMore = true;
    dt_loadingMore = false;
    mt_page = 1;
    mt_hasMore = true;
    mt_loadingMore = false;

    var that = this;
    //初始化底部导航
    var b_nav_data = app.getBottomNavData('zixun/zixun', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor,
        tc: app.get_tc()
      });
    });

    var titlename = '最新消息';
    wx.setNavigationBarTitle({
      title: titlename,
    })

    wx.getSystemInfo({
      success: function (res) {
        var wid_1 = res.windowWidth - 25;
        var wid_2 = (res.windowWidth - 35) / 2;
        var wid_3 = (res.windowWidth - 45) / 3;
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          wz_item_img_w_1: wid_1,
          wz_item_img_w_2: wid_2,
          wz_item_img_w_3: wid_3,
          wz_item_img_h_1: wid_1 / 2,
          wz_item_img_h_2: wid_2,
          wz_item_img_h_3: wid_3,
        })
      }
    })

    reload = true;
    //当前登录用户信息
    app.LoginUserInfo(function (res) {
      var authFail = res == -1;//用户拒绝授权
      if (!authFail) {
        //更新数据
        that.setData({
          uid: res.uid,
          token: res.token,
          openid: res.wxsmall_openid
        }); 
        that.getEditAuth(); 
      }
      
    });
    //获取专辑
    that.getalbum();
    //时尚动态 （相册子分类）
    that.loadDt(1);
   
  },

  getalbum:function(){
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getalbum",
      type: '8',
      uid: util.orgid,
      page: 1,
      num: 10
    }
    console.log("getalbum", params);
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("getalbum", result);
        if(result.res == false){

        }else{
          for(var i=0;i<result.length;i++){
            if(result[i].id == 49){
              that.setData({
                album:result[i]
              })
            }
          }
        }
      }
    });
  },

  //获取当前登录用户是否有权限编辑该数据
  getEditAuth: function () {
    var that = this;
    var params = {
      "publickey": util.publiccode,
      "ac": "adminuser"
    };
    console.log("获取管理组人员id参数：", params);
    util.api({
      data: params,
      success: function (responseData) {
        console.log("获取管理组人员数据：", responseData);
        if (responseData.data.res) {
          var authUsers = responseData.data.mauid.split(',');
          if (that.data.uid) {
            for (var i = 0; i < authUsers.length; i++) {
              if (that.data.uid == authUsers[i]) {
                that.setData({
                  canEdit: true
                });
                var timestamp = Date.parse(new Date());
                timestamp = timestamp / 1000;
                break;
              }
            }
          }
        }
      }
    });
  },

  showDt: function () {
    this.setData({
      curr: {
        dt: "curr",
        mt: ""
      }
    });
  },

  showMt: function () {
    this.setData({
      curr: {
        dt: "",
        mt: "curr"
      }
    });
  },

  loadMore: function (e) {
    var cName = e.currentTarget.dataset.con;
    if (cName == "dt") {
      if (dt_hasMore && !dt_loadingMore) {
        dt_loadingMore = true;
        dt_page ++;
        this.loadDt(dt_page);
      } else {
        console.log("没有更多了");
      }
    } else if (cName == "mt") {
      if (mt_hasMore && !mt_loadingMore) {
        mt_loadingMore = true;
        mt_page++;
        this.loadMt(mt_page);
      } else {
        console.log("没有更多了");
      }
    }
  },

  // 读取动态 （近况）
  loadDt: function (cpage) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "topiclist",
      topictype: '8',
      albumid: '49',
      //tc: that.data.tc,
      postuid: util.orgid,
      toporder: 1,
      page: cpage,
      num: 10
    }
    console.log("loadDt请求近况：", params);
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("请求近况返回：", result);
        if (!result.msg) {
          result.forEach(function (m, i) {
            if (m.photos) {
              result[i].photosData = m.photos.split(",");
            }
            result[i].message = app.parseHTMLText(m.message);
            result[i].dateline = that.toDate(result[i].dateline);
          });
         
          if (cpage <= 1) {
            
            that.setData({
              dongtaiData: result
            });
          } else {
            that.setData({
              dongtaiData: that.data.dongtaiData.concat(result)
            });
          }
        } else {
          if (cpage <= 1) {
            that.setData({
              dongtaiData: []
            });
          }
          dt_hasMore = false;
        }
        dt_loadingMore = true;

        if (that.data.dongtaiData.length <= 0) {
          that.setData({
            hasDongtai: false
          })
        } else {
          that.setData({
            hasDongtai: true
          })
        }
        wx.hideLoading();
      }
    });
  },

  // 读取媒体 
  loadMt: function (cpage) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "topiclist",
      topictype: '8',
      //tc: that.data.tc,
      albumid: '49',
      postuid: util.orgid,
      toporder: 1,
      page: cpage,
      num: 10
    }
    console.log("loadMt请求近况：", params);
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("请求近况返回：", result);
        if (!result.msg) {
          result.forEach(function (m, i) {
            if (m.photos) {
              result[i].photosData = m.photos.split(",");
            }
            result[i].message = app.parseHTMLText(m.message);
          });
          if (cpage <= 1) {
            that.setData({
              meitiData: result
            });
          } else {
            that.setData({
              meitiData: that.data.meitiData.concat(result)
            });
          }
        } else {
          if (cpage <= 1) {
            that.setData({
              meitiData: []
            });
          }
          mt_hasMore = false;
        }
        mt_loadingMore = true;

        if (that.data.meitiData.length <= 0) {
          that.setData({
            hasMeiti: false
          })
        } else {
          that.setData({
            hasMeiti: true
          })
        }
        wx.hideLoading();
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if(path) {
      if (path.indexOf('navto:') == 0) {
        var navPath = path.slice(6);
        wx.navigateTo({
          url: navPath,
        })
      } else {
        wx.redirectTo({ url: path });
      }
    }
  },

   //时间戳转换时间  
  toDate: function (number) {
    var n = number * 1000;
    var date = new Date(n);
    var Y = date.getFullYear() + '/';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    // var H = date.getHours() < 10 ? '0'+date.getHours():date.getHours();
    // var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    return (Y + M + D)
  },
})